package com.smartcity.domain.query;

import com.baomidou.mybatisplus.annotation.OrderBy;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Data
@Schema(description = "分页查询实体")
public class PageQuery {
    @Schema(description = "页码")
    @Min(value = 1, message = "页码必须大于0")
    @NotNull(message = "页码不能为空")
    public Long pageNo;
    @Schema(description ="每页大小")
    @Min(value = 1, message = "每页大小必须大于0")
    @NotNull(message = "每页大小不能为空")
    public Long pageSize;
    @Schema(description ="排序字段,多个用逗号分隔，字段名后加:desc表示降序，默认升序")
    public String sortBy;




    public <T> Page<T> page(){
        // 1.分页条件
        Page<T> page = Page.of(pageNo, pageSize);
        // 2.排序条件
        // 2.1.先看前端有没有传排序字段
        if(StringUtils.isNullOrEmpty(sortBy))
        {
            String[] orderList = sortBy.split(",");
            List<OrderItem> orderItems = Stream.of(orderList).map(o -> {
                String[] arr = o.split(":");
                boolean isAsc = arr.length == 1 || "asc".equals(arr[1]);
                OrderItem orderItem = new OrderItem();
                orderItem.setColumn(arr[0]);
                orderItem.setAsc(isAsc);
                return orderItem;
            }).collect(Collectors.toList());
            page.setOrders(orderItems);
        }

        return page;
    }


}